package com.li.general.text
{
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;

public class TextRandomizer
{
    private var _textfield:TextField;
    private var _targetText:String;
    private var _renderTmr:Timer;
    private var _charMarker:uint;
    private var _tries:uint;

    public var fillString:String = "-";
    public var maxTries:uint = 5;
    public var stepTime:uint = 5;

    public function TextRandomizer(textfield:TextField)
    {
        _textfield = textfield;
        
        _renderTmr = new Timer(stepTime);
        _renderTmr.addEventListener(TimerEvent.TIMER, renderTimerHandler);
    }

    public function setText(value:String):void
    {
        _textfield.text = "";
        _targetText = value;
        _charMarker = 0;
        _renderTmr.start();
    }

    private function renderTimerHandler(evt:TimerEvent):void
    {
        // Fill characters.
        if(_textfield.text.length < _targetText.length)
            _textfield.text = _textfield.text + fillString;

        // Match characters.
        else if(_textfield.text.charAt(_charMarker) != _targetText.charAt(_charMarker))
        {
            var prev:String = _textfield.text.substring(0, _charMarker);
            var next:String = _textfield.text.substring(_charMarker + 1, _textfield.text.length);

            var replace:String;
            if(_tries < maxTries)
            {
                var rand:uint = Math.floor((126 - 32)*Math.random()) + 32;
                replace = String.fromCharCode(rand);
            }
            else
            {
                _tries = 0;
                replace = _targetText.charAt(_charMarker);
            }

            _textfield.text = prev + replace + next;

            _tries++;
        }
        else
        {
            _charMarker++;
            _tries = 0;
        }

        if(_charMarker == _targetText.length)
            _renderTmr.stop();
    }
}
}